package com.smart.community.common.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 子未语
 */
@Configuration
public class RedisConfig {

    /**
     * 用于创建Redis的数据库连接
     *
     * @param connectionFactory 连接工厂对象
     * @return 返回值用于简化与Redis的交互模板
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        // 创建StringRedisSerializer将字符串进行序列化
        StringRedisSerializer keyRedisSerializer = new StringRedisSerializer();
        redisTemplate.setStringSerializer(keyRedisSerializer);
        redisTemplate.setHashKeySerializer(keyRedisSerializer);
        // 创建一个GenericJackson2JsonRedisSerializer对象，用于序列化对象为JSON格式。
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        return redisTemplate;
    }




    /**
     * 获取到操作Redis数据库的对象
     *
     * @param redisTemplate 操作Redis数据库的模板
     * @return 操作Redis数据库的操作对象
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }
}